package com.renovate.portal.activities;

import java.io.IOException;

import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.renovate.portal.R;
import com.renovate.portal.fragments.DisplayFragment;
import com.renovate.portal.fragments.MenuFragment;
import com.renovate.portal.util.ConnectionDetector;
import com.renovate.portal.util.Helpers;
import com.htc.app.SlidingActivity;
import com.htc.util.HtcCommonUtil;
import com.htc.widget.ActionBarContainer;
import com.htc.widget.ActionBarExt;
import com.htc.widget.ActionBarText;
import com.htc.widget.HtcAlertDialog;
import com.htc.widget.SlidingMenu;

public class MainActivity extends SlidingActivity {
	ConnectionDetector cd;
	Boolean isInternetPresent = false;
	String versionName = null;
	private Fragment mContent;
	private boolean mExitFlag = false;
	private long mExitBackTimeout = -1;
	private static final int RELEASE_EXIT_CHECK_TIMEOUT = 3500;

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.layout.actionbar_actions_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem menuitem) {
		boolean flag = true;
		switch (menuitem.getItemId()) {
		case android.R.id.home:
			toggle();
			break;
		}
		return flag;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		try {
			@SuppressWarnings("unused")
			Process p = Runtime.getRuntime().exec("su");
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			versionName = getPackageManager().getPackageInfo(getPackageName(),
					0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		super.onCreate(savedInstanceState);

		// set the Above View
		if (savedInstanceState != null)
			mContent = getFragmentManager().getFragment(savedInstanceState,
					"mContent");
		if (mContent == null)
			mContent = new DisplayFragment();

		// set the Above View
		setContentView(R.layout.content_frame);
		getFragmentManager().beginTransaction()
				.replace(R.id.content_frame, mContent).commit();

		// set the Behind View
		setBehindContentView(R.layout.menu_frame);
		getFragmentManager().beginTransaction()
				.replace(R.id.menu_frame, new MenuFragment()).commit();

		// customize the SlidingMenu
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		setSlidingActionBarEnabled(false);

		cd = new ConnectionDetector(getApplicationContext());
		isInternetPresent = cd.isConnectingToInternet();
		if (isInternetPresent) {
		} else {
			HtcAlertDialog.Builder aDialog = new HtcAlertDialog.Builder(
					MainActivity.this);
			aDialog.setCancelable(false);
			aDialog.setTitle(R.string.network_error);
			aDialog.setMessage(R.string.network_message);
			aDialog.setPositiveButton(R.string.open_settings,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(Intent.ACTION_MAIN);
							intent.setClassName("com.android.settings",
									"com.android.settings.wifi.WifiSettings");
							startActivity(intent);
							finish();
						}
					});
			aDialog.setNegativeButton(R.string.exit,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			aDialog.show();

		}

		// robust kang prevention
		if ((Helpers.getROMVersion().contains("Renovate"))) {
			Log.i("mwilky", "Running on Renovate");
		} else {
			Log.e("mwilky", "Incompatible ROM!");
			finish();
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		getFragmentManager().putFragment(outState, "mContent", mContent);
	}

	public void switchContent(Fragment fragment) {
		mContent = fragment;
		getFragmentManager().beginTransaction()
				.replace(R.id.content_frame, fragment).commit();
		getSlidingMenu().showContent();
	}

	private boolean checkBackAction() {

		// Do back operation over the navigation history
		boolean flag = this.mExitFlag;

		this.mExitFlag = !back();

		// Retrieve if the exit status timeout has expired
		long now = System.currentTimeMillis();
		boolean timeout = (this.mExitBackTimeout == -1 || (now - this.mExitBackTimeout) > RELEASE_EXIT_CHECK_TIMEOUT);

		// Check if there no history and if the user was advised in the last
		// back action
		if (this.mExitFlag && (this.mExitFlag != flag || timeout)) {
			// Communicate the user that the next time the application will be
			// closed
			this.mExitBackTimeout = System.currentTimeMillis();
			Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT)
					.show();
			return true;
		}

		// Back action not applied
		return !this.mExitFlag;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (checkBackAction()) {
				return true;
			}

			finish();
		}
		return super.onKeyUp(keyCode, event);
	}

	public boolean back() {

		// Nothing to apply
		return false;
	}
}
